package com.handinglian.employee.controller;

import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.view.PoiBaseView;
import cn.hutool.core.util.StrUtil;
import com.apidoc.annotation.Api;
import com.apidoc.annotation.ApiVersion;
import com.github.pagehelper.PageInfo;
import com.handinglian.common.dto.ResultData;
import com.handinglian.common.factory.ResultDataFactory;
import com.handinglian.common.shiro.Principal;
import com.handinglian.common.utils.FastJsonUtil;
import com.handinglian.employee.dto.*;
import com.handinglian.employee.entity.FileInfo;
import com.handinglian.employee.entity.UserInfo;
import com.handinglian.employee.param.*;
import com.handinglian.employee.service.FileInfoService;
import com.handinglian.employee.service.UserInfoService;
import com.handinglian.employee.service.UserTagService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Api("用户")
@Slf4j
@RestController
@RequestMapping("/{version}/user")
@ApiVersion(1.0)
public class UserInfoController {
    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private UserTagService userTagService;
    @Autowired
    private FileInfoService fileInfoService;

    /**
     * 创建用户
     */
    @RequiresPermissions("employee_list:create")
    @PostMapping(value = "/createUserInfo")
    public ResultData createUserInfo(@RequestBody UserCreateParam userCreateParam) throws IOException, DocumentException {
        UserInfo userInfo = userInfoService.loadInvalidUserInfo(userCreateParam.getJobNum());
        if (userInfo != null){
            return ResultData.existsInHistory();
        }
        return userInfoService.createUserInfo(userCreateParam);
    }

    /**
     * 从删除列表中恢复用户
     */
    @RequiresPermissions("employee_list:update")
    @PutMapping(value = "/recoverUserInfo")
    public ResultData recoverUserInfo(@RequestBody UserRecoverParam userRecoverParam) throws IOException, DocumentException {
        int amount = userInfoService.recoverUserInfo(userRecoverParam.getJobNum());
        return ResultDataFactory.generateResultData(amount);
    }

    /**
     * 删除用户
     */
    @RequiresPermissions("employee_list:delete")
    @DeleteMapping(value = "/deleteUserInfo")
    public ResultData deleteUserInfo(Integer userId) throws IOException, DocumentException {
        int amount = userInfoService.deleteUserInfo(userId);
        return ResultDataFactory.generateResultData(amount);
    }

    /**
     * 更新用户
     */
    @RequiresPermissions("employee_list:update")
    @PutMapping(value = "/updateUserInfo")
    public ResultData updateUserInfo(@RequestBody UserUpdateParam userUpdateParam) {
        int amount = userInfoService.updateUserInfo(userUpdateParam);
        return ResultDataFactory.generateResultData(amount);
    }

    /**
     * 更新系统用户
     */
    @RequiresPermissions("employee_list:update")
    @PutMapping(value = "/updateSystemUser")
    public ResultData updateSystemUser(@RequestBody SystemUserParam systemUserParam) {
        int amount = userInfoService.updateSystemUser(systemUserParam);
        return ResultDataFactory.generateResultData(amount);
    }

    /**
     * 创建系统用户
     */
    @RequiresPermissions("employee_list:create")
    @PostMapping(value = "/createSystemUser")
    public ResultData createSystemUser(@RequestBody SystemUserParam systemUserParam) {
        int amount = userInfoService.createSystemUser(systemUserParam);
        return ResultDataFactory.generateResultData(amount);
    }

    /**
     * 删除系统用户
     */
    @RequiresPermissions("employee_list:delete")
    @DeleteMapping(value = "/deleteSystemUser")
    public ResultData deleteSystemUser(Integer userId) {
        int amount = userInfoService.deleteSystemUser(userId);
        return ResultDataFactory.generateResultData(amount);
    }


    /**
     * 查询用户信息
     */
    @RequiresPermissions("employee_list:list")
    @GetMapping(value = "/loadUserInfo")
    public ResultData<UserInfoDto> loadUserInfo(Integer userId) {
        UserInfoDto userInfo = userInfoService.loadUserInfo(userId);
        return ResultDataFactory.generateSuccessResultData(userInfo);
    }

    /**
     * 查询系统用户信息
     */
    @RequiresPermissions("employee_list:list")
    @GetMapping(value = "/loadSystemUserInfo")
    public ResultData<SystemUserInfoDto> loadSystemUserInfo(Integer userId) {
        SystemUserInfoDto systemUserInfoDto = userInfoService.loadSystemUserInfo(userId);
        return ResultDataFactory.generateSuccessResultData(systemUserInfoDto);
    }

    /**
     * 通过工号查询用户(common)
     */
    @RequiresPermissions("employee_list:list")
    @GetMapping(value = "/loadUserInfoByJobNum")
    public ResultData<UserInfoDetailDto> loadUserInfoByJobNum(String jobNum) {
        UserInfoDetailDto userInfoDetailDto = userInfoService.loadUserDetailByJobNum(jobNum);
        if (StrUtil.isNotBlank(userInfoDetailDto.getImageId())){
            FileInfo fileInfo = fileInfoService.loadFile(userInfoDetailDto.getImageId());
            if (fileInfo != null){
                userInfoDetailDto.setImagePath(fileInfo.getFilePath());
            }
        }

        return ResultDataFactory.generateSuccessResultData(userInfoDetailDto);
    }

    /**
     * 获取用户分页列表
     */
    @RequiresPermissions("employee_list:list")
    @GetMapping("/inquireUserInfoPageList")
    public ResultData<PageInfo<UserInfoDto>> inquireUserInfoPageList(Principal principal, String nameOrJobNumOrPhone, String departmentName, String sexs, String phonePermissions, Integer pageIndex, Integer pageSize){
        PageInfo<UserInfoDto> userInfoPageInfo = userInfoService.inquireUserInfoPageList(principal.getUserId(), nameOrJobNumOrPhone, departmentName, sexs, phonePermissions, pageIndex, pageSize);
        return ResultDataFactory.generateSuccessResultData(userInfoPageInfo);
    }

    /**
     * 获取系统用户分页列表
     */
    @RequiresPermissions("employee_list:list")
    @GetMapping("/inquireSystemUserInfoPageList")
    public ResultData<PageInfo<SystemUserInfoDto>> inquireSystemUserInfoPageList(Principal principal, String nameOrJobNumOrPhone, String loginStates, Integer pageIndex, Integer pageSize){
        PageInfo<SystemUserInfoDto> userInfoPageInfo = userInfoService.inquireSystemUserInfoPageList(principal.getUserId(), nameOrJobNumOrPhone, loginStates, pageIndex, pageSize);
        return ResultDataFactory.generateSuccessResultData(userInfoPageInfo);
    }

    /**
     * 员工信息模板导出
     */
    @RequiresPermissions("employee_list:list")
    @GetMapping("/exportUserTemplateExcel")
    public void exportUserTemplateExcel(ModelMap map, HttpServletRequest request, HttpServletResponse response) {
        ExportParams params = new ExportParams("员工信息", "员工信息", ExcelType.XSSF);
        map.put(NormalExcelConstants.DATA_LIST, new ArrayList<>());
        map.put(NormalExcelConstants.CLASS, UserTemplateExcel.class);
        map.put(NormalExcelConstants.PARAMS, params);
        map.put(NormalExcelConstants.FILE_NAME, "导入员工");
        PoiBaseView.render(map, request, response, NormalExcelConstants.EASYPOI_EXCEL_VIEW);
    }

    /**
     * 员工信息导出
     */
    @GetMapping("/exportUserInfoExcel")
    public void exportUserInfoExcel(ModelMap map, HttpServletRequest request, HttpServletResponse response) {
        List<UserInfoDto> userInfoDtos = userInfoService.list();
        List<UserInfoExcel> userInfoExcels = FastJsonUtil.ListToList(userInfoDtos, UserInfoExcel.class);
        userInfoExcels.forEach(userInfoExcel -> {
            String sex = userInfoExcel.getSex();
            sex = StrUtil.isBlank(sex)?"保密":sex.equals("1")?"男":"女";
            userInfoExcel.setSex(sex);

            String phonePermission = userInfoExcel.getPhonePermission();
            phonePermission = StrUtil.isBlank(phonePermission)?"未知":phonePermission.equals("1")?"开启":"关闭";
            userInfoExcel.setPhonePermission(phonePermission);
        });
        ExportParams params = new ExportParams("员工信息", "员工信息", ExcelType.XSSF);
        map.put(NormalExcelConstants.DATA_LIST, userInfoExcels);
        map.put(NormalExcelConstants.CLASS, UserInfoExcel.class);
        map.put(NormalExcelConstants.PARAMS, params);
        map.put(NormalExcelConstants.FILE_NAME, "员工信息");
        PoiBaseView.render(map, request, response, NormalExcelConstants.EASYPOI_EXCEL_VIEW);
    }

    /**
     * 员工信息导入
     */
    @RequiresPermissions("employee_list:create")
    @PostMapping("/importUserTemplateExcel")
    public ResultData importUserTemplateExcel(ModelMap map, HttpServletRequest request, HttpServletResponse response,  MultipartFile file, Integer flag) throws Exception {
        ImportUserDto importUserDto = userInfoService.importUserTemplateExcel(map, request, response, file, flag);

        return ResultDataFactory.generateSuccessResultData(importUserDto);
    }

    /**
     * 查询分机信息(common)
     */
    @RequiresPermissions("employee_list:list")
    @GetMapping("/loadExtensionByJobNum")
    public ResultData<ExtensionDto> loadExtensionByJobNum(String jobNum) {
        ExtensionDto extensionDto =userInfoService.loadExtensionByJobNum(jobNum);
        return ResultDataFactory.generateSuccessResultData(extensionDto);
    }

    /**
     * 通过部门id查询用户信息(common)
     */
    @RequiresPermissions("employee_list:list")
    @GetMapping("/inquireUserInfoByDepartmentId")
    public ResultData<UserInfoDto> inquireUserInfoByDepartmentId(Integer departmentId, String nameOrPhone) {
        List<UserInfoDto> userInfoDtos =userInfoService.inquireUserInfoByDepartmentId(departmentId, nameOrPhone);
        return ResultDataFactory.generateSuccessResultData(userInfoDtos);
    }

    /**
     * 员工上传头像(APP)
     */
    @RequiresPermissions("employee_list:create")
    @PostMapping("/uploadHeadImage")
    public ResultData uploadHeadImage(MultipartFile file, Integer userId) throws Exception {
        String filePath = userInfoService.uploadHeadImage(file, userId);
        return ResultDataFactory.generateSuccessResultData(filePath);
    }

    /**
     * 员工下载头像(APP)
     */
    @RequiresPermissions("employee_list:create")
    @PostMapping("/downloadHeadImage")
    public ResultData downloadHeadImage(HttpServletResponse response, String fileUuid) throws Exception {
        userInfoService.downloadHeadImage(response, fileUuid);
        return ResultDataFactory.generateResultData(null);
    }

    /**
     * 创建用户标签(APP)
     */
    @PostMapping("/createUserTag")
    public ResultData createUserTag(@RequestBody UserTagCreateParam userTagCreateParam) throws Exception {
        int amount = userTagService.createUserTag(userTagCreateParam);
        return ResultDataFactory.generateResultData(amount);
    }

    /**
     * 删除用户标签(APP)
     */
    @DeleteMapping("/deleteUserTag")
    public ResultData deleteUserTag(Integer userTagId) throws Exception {
        int amount = userTagService.deleteUserTag(userTagId);
        return ResultDataFactory.generateResultData(amount);
    }

    /**
     * 查询用户标签(APP)
     */
    @GetMapping("/inquireUserTagList")
    public ResultData<UserTagDto> inquireUserTagList(Integer userId) {
        return ResultDataFactory.generateSuccessResultData(userTagService.inquireUserTagList(userId));
    }

    /**
     * 修改密码(common)
     */
    @RequiresPermissions("employee_list:update")
    @PutMapping("/updatePassword")
    public ResultData updatePassword(@RequestBody UpdatePasswordParam updatePasswordParam) {
        int amount = userInfoService.updatePassword(updatePasswordParam);
        return ResultDataFactory.generateResultData(amount);
    }

    /**
     * 重置密码
     */
    @RequiresPermissions("employee_list:reset")
    @PutMapping("/resetPassword")
    public ResultData resetPassword(@RequestBody PasswordResetParam passwordResetParam) {
        int amount = userInfoService.resetPassword(passwordResetParam.getUserId());
        return ResultDataFactory.generateResultData(amount);
    }

    /**
     * 开启关闭管理端登录权限
     */
    @RequiresPermissions("employee_list:update")
    @PutMapping("/updateLoginState")
    public ResultData updateLoginState(@RequestBody LoginStateUpdateParam loginStateParam) {
        int amount = userInfoService.updateLoginState(loginStateParam);
        return ResultDataFactory.generateResultData(amount);
    }

    /**
     * 查询pushId
     */
    @GetMapping("/getPushId")
    public ResultData getPushId(String jobNum) {
        return ResultDataFactory.generateSuccessResultData(userInfoService.findPushIdByJobNum(jobNum));
    }

    /**
     * 查询pushId
     */
    @GetMapping("/pushAll")
    public ResultData pushAll() throws IOException {
        userInfoService.pushAll();
        return ResultDataFactory.generateSuccessResultData(null);
    }
}
